package cn.com.bluemoon.daps.system.cron;

import cn.com.bluemoon.daps.common.enums.BmStatus;
import cn.com.bluemoon.daps.system.dto.WechatDeptDto;
import cn.com.bluemoon.daps.system.entity.DapSystemDepartment;
import cn.com.bluemoon.daps.system.mapper.DapSystemDepartmentMapper;
import cn.com.bluemoon.daps.system.mapper.DapSystemWechatDeptMapper;
import cn.com.bluemoon.daps.system.service.DapSystemWechatDeptService;
import cn.com.bluemoon.daps.system.vo.DapSystemWechatDeptTreeVo;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 每天中午12点拉取一次企业微信部门数据到mysql
 *
 * @author Jarod.Kong
 */
@Component
@EnableScheduling
@EnableAsync
public class DapScheduleBean {

    @Value("${daps.dept.scanUrl:https://wechat.bluemoon.com.cn/wl-service/qyweixin/department/departmentList?corpId=wx36ef368cf28caea0}")
    private String url;

    @Resource(name = "customRestTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private DapSystemWechatDeptService systemWechatDeptService;

    @Autowired
    private DapSystemWechatDeptMapper dapSystemWechatDeptMapper;

    @Autowired
    private DapSystemDepartmentMapper dapSystemDepartmentMapper;

    @Bean(name = "customRestTemplate")
    public RestTemplate customRestTemplate() {
        return new RestTemplate();
    }

    @Async
//    @Scheduled(fixedRate = 3000)
//    @Scheduled(cron = "${daps.dept.cron:0 0 12 * * ?}")
    public void scanWeChatDept() {
        ResponseEntity<ResponseEntityVo> resp = restTemplate.getForEntity(url, ResponseEntityVo.class);
        ResponseEntityVo entityVo = resp.getBody();
        if (entityVo != null && Boolean.TRUE.equals(entityVo.getSuccess())) {
            List<WechatDeptDto> res = getDeptVos(entityVo);
            if (!res.isEmpty()) {
                dapSystemWechatDeptMapper.upsert(res);
                List<DapSystemDepartment> sysDept = getDapSystemDepartments();
                dapSystemDepartmentMapper.upsert(sysDept);
            }
        }

    }

    private List<DapSystemDepartment> getDapSystemDepartments() {
        // 排除已有的部门
        List<DapSystemDepartment> departments = dapSystemDepartmentMapper.selectList(Wrappers.<DapSystemDepartment>lambdaQuery().eq(DapSystemDepartment::getBmStatus, BmStatus.ON));
        Set<String> departNames = departments.stream().map(DapSystemDepartment::getDepartName).collect(Collectors.toSet());
        List<DapSystemWechatDeptTreeVo> deptTreeVos = systemWechatDeptService.getDapSystemWechatDeptTreeVos(3);
//                List<DapSystemWechatDept> wechatDept = systemWechatDeptService.getDapSystemWechatDeptByIds(deptTreeVos.stream().map(DapSystemWechatDeptTreeVo::getParentid).collect(Collectors.toList()));
//                Map<Integer, String> parentIdNames = wechatDept.stream().collect(Collectors.toMap(DapSystemWechatDept::getId, DapSystemWechatDept::getName));
        List<DapSystemDepartment> sysDept = deptTreeVos.stream().filter(d -> {
            return !departNames.contains(d.getName());
        }).map(d -> {
            DapSystemDepartment dept = new DapSystemDepartment();
            dept.setDepartName(d.getName());
            dept.setDepartCode(d.getId() + "");
            dept.setDepartLeader(null);
            dept.setPidDepartCode(null);
            int snowflakeIdLength = "1336839530462777345".length();
            String stdId = d.getId() + String.format("%0" + (snowflakeIdLength - (d.getId() + "").length()) + "d", 0);
            dept.setId(stdId);
            dept.setCreateBy("system");
            dept.setCreateTime(LocalDateTime.now());
            dept.setUpdateBy("system");
            dept.setUpdateTime(LocalDateTime.now());
            dept.setBmStatus(BmStatus.ON);
            return dept;
        }).collect(Collectors.toList());
        return sysDept;
    }

    private List<WechatDeptDto> getDeptVos(ResponseEntityVo entityVo) {
        List<WechatDeptDto> res = new ArrayList<>();
        Object entityVoData = entityVo.getData();
        if (entityVoData instanceof List) {
            @SuppressWarnings("unchecked") List<LinkedHashMap<String, Object>> data = (List<LinkedHashMap<String, Object>>) entityVoData;
            res = data.stream().map(d -> {
                return WechatDeptDto.builder().id(NumberUtil.parseInt(String.valueOf(d.getOrDefault("id", null))))
                        .name(String.valueOf(d.getOrDefault("name", null)))
                        .parentid(NumberUtil.parseInt(String.valueOf(d.getOrDefault("parentid", null))))
                        .wxOrder(NumberUtil.parseInt(String.valueOf(d.getOrDefault("order", null))))
                        .build();
            }).collect(Collectors.toList());
        }
        return res;
    }

    @Data
    public static class ResponseEntityVo {
        private Integer responseCode;
        private String responseMsg;
        private Object data;
        private Boolean success;
    }
}
